﻿using System.Reflection;

namespace DB2WORD.Logics
{
    public static class ControlExtensions
    {
        private static PropertyInfo? piDoubleBuffered = typeof(Control).GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
        private static MethodInfo? miSetStyle = typeof(Control).GetMethod("SetStyle", BindingFlags.Instance | BindingFlags.NonPublic);
        private static MethodInfo? miUpdateStyles = typeof(Control).GetMethod("UpdateStyles", BindingFlags.Instance | BindingFlags.NonPublic);

        public static void SetDoubleBuffer(this Control control)
        {
            miSetStyle?.Invoke(control, new object[] { ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint, true });
            miUpdateStyles?.Invoke(control, null);

            //利用反射设置双缓冲
            piDoubleBuffered?.SetValue(control, true, null);
        }

        public static async Task Delay(this Control control, int millisecondsDelay = 3000, Action? action = null)
        {
            control.Enabled = false;
            await Task.Delay(millisecondsDelay).ContinueWith(t =>
            {
                if(action != null)
                {
                    if(control.InvokeRequired)
                    {
                        control.Invoke(action);
                    }
                    else
                    {
                        action();
                    }
                }
                control.Enabled = true;
            });
        }
    }
}
